﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using XCBPM.Mobile.BLL;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using spUtils;
using System.Data;
using XCBPM.Mobile.Common;

namespace XCBPM.Mobile.Services
{
    /// <summary>
    /// 移动审批接口
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class UltimusMobileService : System.Web.Services.WebService
    {
        /// <summary>
        /// AD用户登录验证
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true), WebMethod]
        public int UserLoginCheck(string accountName, string password)
        {
            string currentDomainName = SysContext.CurrentDomainName;
            UserDomainCheck check = new UserDomainCheck();
            if (check.impersonateValidUser(accountName, currentDomainName, password))
            {
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 获取表单HTML
        /// </summary>
        /// <param name="ProcInstID"></param>
        /// <param name="HtmlWidth"></param>
        /// <param name="HtmlType"></param>
        /// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true), WebMethod]
        public string GetTableHTML(string ProcInstID, string HtmlWidth, string HtmlType)
        {
            string html = string.Empty;
            string path = Server.MapPath("~/") + "Forms\testhtml.txt";
            string bodyTemplate = FormMethod.ReadFile(path);

            string pattern1 = @"<table.*?<\/table>";
            RegexOptions options = RegexOptions.None | RegexOptions.IgnoreCase | RegexOptions.Singleline;
            Regex regex1 = new Regex(pattern1, options);
            MatchCollection matches1 = regex1.Matches(bodyTemplate);
            string bodyHTML = string.Empty;
            foreach (Match matchTable in matches1)
            {
                List<String> tdList = new List<string>();
                StringBuilder sb = new StringBuilder();
                sb.Append("<table>");
                string pattern2 = @"<tr.*?</tr>";
                Regex regex2 = new Regex(pattern2, options);
                MatchCollection matches2 = regex2.Matches(matchTable.Value);
                foreach (Match matchTR in matches2)
                {
                    string pattern3 = @"<td.*?</td>";
                    Regex regex3 = new Regex(pattern3, options);
                    MatchCollection matches3 = regex3.Matches(matchTR.Value);
                    foreach (Match matchTD in matches3)
                    {
                        tdList.Add(matchTD.Value);
                    }
                }
                foreach (string td in tdList)
                {

                }
                sb.Append("</table>");
                bodyHTML += sb.ToString();
            }
            return bodyHTML;
        }

        /// <summary>
        /// 我的待办
        /// </summary>
        /// <param name="CurrentUserId"></param>
        /// <param name="processID"></param>
        /// <param name="ProcInstID"></param>
        /// <param name="PageNo"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true), WebMethod]
        public string MyToDoJs(string currentUserName, string ProcessName, int PageNo, int PageSize)
        {
            ProcessTasks tasks = new ProcessTasks();
            DataTable dtMyJobs = tasks.GetMyToDoJob(currentUserName, ProcessName, PageNo, PageSize);
            return JsonHelper.DataTableToJSON(dtMyJobs,"DataTable");

        }

        /// <summary>
        /// 我处理过的流程
        /// </summary>
        /// <param name="ProcInstID"></param>
        /// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true), WebMethod]
        public string MyAlReadyFlowJs(string currentUserName, string ProcessName, int PageNo, int PageSize)
        {
            ProcessTasks tasks = new ProcessTasks();

            DataTable dtMyJobs = tasks.GetMyToDoJob(currentUserName, ProcessName, PageNo, PageSize);

            return JsonHelper.DataTableToJSON(dtMyJobs, "DataTable");

        }

        /// <summary>
        /// 我发起的流程
        /// </summary>
        /// <param name="CurrentUserId"></param>
        /// <param name="processID"></param>
        /// <param name="ProcInstID"></param>
        /// <param name="PageNo"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
        public string MyStartFlowJs(string currentUserName, string ProcessName, int PageNo, int PageSize)
        {
            ProcessTasks tasks = new ProcessTasks();

            DataTable dtMyJobs = tasks.MyStartFlowJs(currentUserName, ProcessName, PageNo, PageSize);

            return JsonHelper.DataTableToJSON(dtMyJobs, "DataTable");
        }

        /// <summary>
        /// 流程审批
        /// </summary>
        /// <param name="approval"></param>
        /// <param name="comment"></param>
        /// <param name="jobID"></param>
        /// <param name="currentUserID"></param>
        /// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false), WebMethod]
        public string ExecApproval(string processName, int incidentNumber, string stepName, string currentUserID, string comment, int approval)
        {
            int num;
            string message = string.Empty;
            try
            {
                string outMsg = string.Empty;
                XCBPM.Mobile.Service.UltimusAPI.API client = new XCBPM.Mobile.Service.UltimusAPI.API();
                //approval = 2;
                //XCBPM.Mobile.Service.UltimusAPI.Variable variable = new XCBPM.Mobile.Service.UltimusAPI.Variable();
                //variable.strVariableName = "Step";
                //variable.objVariableValue = new object[] { approval };

                XCBPM.Mobile.Service.UltimusAPI.Variable[] arrVariable = new XCBPM.Mobile.Service.UltimusAPI.Variable[] { };

                bool isCompleted = client.CompleteStep( processName, currentUserID, incidentNumber, stepName, null, comment, arrVariable,out outMsg);

                //TODO 处理审批意见

                num = 1;
            }
            catch (Exception exception)
            {
                message = exception.Message;
                num = 4;
            }
            return string.Concat(new object[] { "{\"result\":", num, ",\"message\":\"", message, "\"}" });
        }

        /// <summary>
        /// 流程提交
        /// </summary>
        /// <param name="TaskID"></param>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false), WebMethod]
        public void Send(string TaskID)
        {
            TaskApiw TaskAPI = new TaskApiw();
            TaskAPI.Load(TaskID);
            TaskAPI.Send();
        }

        /// <summary>
        /// 流程退回
        /// </summary>
        /// <param name="currentUserId"></param>
        /// <param name="ProcInstID"></param>
        /// <param name="JobID"></param>
        /// <param name="RejectActivity"></param>
        /// <param name="RejectComment"></param>
        /// <param name="rejectStartType"></param>
        /// <returns></returns>
        [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
        public string ExecReject(string currentUserID, int incidentNumber, string processName, string stepName, string RejectComment, int rejectStartType)
        {
            int execResult = 1;
            string message = string.Empty;
            try
            {
                TaskApiw taskApiw = new TaskApiw();
                taskApiw.Load("092215076f545189c2a41c61a2429d");
                //spUtils.TaskApiw taskApiw = new TaskApiw("0922139b94fb1e8fd56a8cec8e2720");
                taskApiw.GoToStep = "填写申请单";
                taskApiw.Send();

               // Service.UltimusAPI.TaskAPI taskApi = new Service.UltimusAPI.TaskAPI();
               // Service.UltimusAPI.API api = new Service.UltimusAPI.API();
               // //spUtils.TaskAp taskApiw = new TaskApiw("0922139b94fb1e8fd56a8cec8e2720");
               // //taskApiw.GoToStep = "填写申请单";
               // //taskApiw.Send();
               // bool result = api.LoadByTaskID("09221508a0931eacfdb873ad1d6ed5", out taskApi);
               //// taskApi.TaskID = "0922139b94fb1e8fd56a8cec8e2720";
               // string outMsg = string.Empty;
               // XCBPM.Mobile.Service.UltimusAPI.API client = new XCBPM.Mobile.Service.UltimusAPI.API();
               // //XCBPM.Mobile.Service.UltimusAPI.Variable[] arrVariable = new XCBPM.Mobile.Service.UltimusAPI.Variable[] {};
               // //bool isCompleted = client.ReturnStep(processName, currentUserID, incidentNumber, stepName, string.Empty, RejectComment, arrVariable,out outMsg);
               //// result = client.DirectActive(taskApi, "填写申请单");
               // //result = client.("092215076f545189c2a41c61a2429d", "xckg/huangwb", out outMsg);                                                

            }
            catch (Exception exception)
            {
                message = exception.Message;
                execResult = 4;
            }
            return string.Concat(new object[] { "{\"result\":", execResult, ",\"message\":\"", message, "\"}" });
        }

        /// <summary>
        /// 退回步骤
        /// </summary>
        /// <param name="jobID"></param>
        /// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true), WebMethod]
        public string ForwardStepJs(string procInstID,string stepName)
        {
            //"\"Name\":\"发起人\",") + "\"Value\":\"草稿\"," + "\"Enabled\":\"1\"
            return "{\"DataTable\":[]}";
        }

        /// <summary>
        /// 审批记录
        /// </summary>
        /// <param name="ProcInstID">流程实例ID</param>
        /// <returns></returns>
        [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
        public string AlReadyApprovalDestJs(string ProcInstID)
        {          
            return "{\"DataTable\":[]}";
            //返回 ActivityName审批步骤| UserName审批人| ApprovalResult审批结果| Comment审批意见| ApprovalDate 审批时间
        }

        /// <summary>
        /// 人员列表
        /// </summary>
        /// <param name="userIdOrName"></param>
        /// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true), WebMethod]
        public string GetUsersByConditionJs(string userIdOrName)
        {
            string jsonStr = string.Empty;
            UserAndDepartmentBLL userAndDepartmentBll = new UserAndDepartmentBLL();
            DataTable dt = userAndDepartmentBll.GetUsersByCondition(userIdOrName);
            if (dt.Rows.Count > 0)
            {
                jsonStr = JsonHelper.DataTableToJSON(dt, "DataTable");
            }
            return jsonStr;
        }

        /// <summary>
        /// 获取附件字节流
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
        public byte[] GetFileBytes(string url)
        {
            FileHelper file = new FileHelper();
            return file.GetFileBytesByUrl(url);
        }
    }
}